package com.proxyhub.schedule;

import com.proxyhub.model.Proxy;
import com.proxyhub.repo.ProxyRepo;
import com.proxyhub.utils.ProxyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 定时验证库中代理的可用性
 * Created by linxsh on 2017/6/30.
 */
@Component
public class ScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleTask.class);

    @Autowired
    private ProxyRepo proxyRepo;

    @Scheduled(fixedRateString = "${schedule.scandb.period}")
    public void scanDbScheduled() {
        logger.info("start scan ip-proxy db");
        List<Proxy> proxies = proxyRepo.findAll();
        for(Proxy proxy : proxies) {
            boolean valid = ProxyUtil.validateProxy(proxy.getHost(), proxy.getPort());
            if(valid) {
                if(proxy.getLastValidDate() == null) {
                    proxy.setLastValidDate(new Date());
                }
            } else {
                proxy.setLastValidDate(null);
            }
            proxy.setValid(valid);
            proxyRepo.saveOrUpdate(proxy);
        }
    }
}
